package com.macro.mall.tiny.service.impl;

import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.service.RedisService;
import com.macro.mall.tiny.service.UmsMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;

/**
 * 会员管管理Service
 *
 * 操作思路：
 * 生成验证码的时候，我们将自定义的Redis键值加上手机号生成一个Redis的key,以验证码为value
 * 存入到Redis中，并设置过期时间(配制文件中定义120s)。校验验证码时候根据手机号来获取redis中
 * 存储的验证码，并与传入的验证码进行对比。
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {

    @Autowired
    private RedisService redisService;

    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.key.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;

    @Override
    public CommonResult generateAuthCode(String telephone) {
        StringBuffer stringBuffer = new StringBuffer();
        Random random = new Random();
        for(int i = 0;i<6;i++){
            stringBuffer.append(random.nextInt(10));
        }
        //验证码绑定手机号并存储到redis中
        redisService.set(REDIS_KEY_PREFIX_AUTH_CODE+telephone,stringBuffer.toString());
        redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE+telephone,AUTH_CODE_EXPIRE_SECONDS);
        return CommonResult.success(stringBuffer.toString(),"获取验证码成功");
    }

    @Override
    public CommonResult verifyAuthCode(String telephone, String authCode) {
        if(StringUtils.isEmpty(authCode)){
            return CommonResult.failed("请输入验证码");
        }
        String realAuthCode = redisService.get(REDIS_KEY_PREFIX_AUTH_CODE+telephone);
        if(authCode.equals(realAuthCode)) {
            return CommonResult.success(null,"验证码检验成功");
        }else {
            return CommonResult.failed("验证码不正确");
        }
    }
}
